﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Diagnostics;

using SharedGenomics.TextMining;
using SharedGenomics.Workbench;

namespace SharedGenomics.Workbench.Services
{
    public class TermineProxy
    {
        private SharedGenomics.Workbench.TermineService.termine_porttypeClient termineClient;

        public TermineProxy()
        {
            this.termineClient = new SharedGenomics.Workbench.TermineService.termine_porttypeClient();
        }

        public ScoredTermCollection Analyse(string text)
        {
            string serviceOutputString = this.termineClient.analyze(text, "plain.genia", "plain", String.Empty, "{JJ}*{NN}+");
            return this.ParseServiceOutput(serviceOutputString);
        }

        private ScoredTermCollection ParseServiceOutput(string output)
        {
            Debug.Assert(output != null);

            ScoredTermCollection terms = new ScoredTermCollection();
            string currentTermLine;
            string[] lineElements;
            double cValue;
            string currentTermText;

            using (StringReader reader = new StringReader(output))
            {
                while ((currentTermLine = reader.ReadLine()) != null)
                {
                    lineElements = currentTermLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    //first item should contain the c-value, the remainder the term
                    if (lineElements.Length >= 2 && Double.TryParse(lineElements[0], out cValue) && cValue > 0.0)
                    {
                        //join remainder of line items to reconstruct the line text
                        currentTermText = String.Join(" ", lineElements, 1, lineElements.Length - 1);

                        //create new ScoredTerm and add to the collection
                        terms.Add(new ScoredTerm(currentTermText, cValue));
                    }
                }
            }

            return terms;
        }
    }
}
